package com.unitylib.alarmnotifyer;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class AlarmNotifyer {
    public static int countStatic = 0;
    public int count = 0;

    public int GetCount(){
        count++;
        Log.d("AlarmNotifyer", "Count:" + count);
        return count;
    }

    public static int GetCountStatic(){
        countStatic++;
        Log.d("AlarmNotifyer", "CountStatic:" + countStatic);
        return countStatic;
    }

    public void SetNotify(String notifyChannelId, String title, String textContent){
        // Create an explicit intent for an Activity in your app
//        Intent intent = new Intent(UnityPlayer.currentActivity, UnityPlayerActivity.class);
//        intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED );
//
//        TaskStackBuilder stackBuilder = TaskStackBuilder.create(UnityPlayer.currentActivity);
//        stackBuilder.addNextIntent(intent);
//        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);//PendingIntent.getActivity(UnityPlayer.currentActivity, 0, intent, PendingIntent.FLAG_MUTABLE);

        //新建Intent用来表示意图
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setComponent(new ComponentName(UnityPlayer.currentActivity, UnityPlayerActivity.class));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        //设置一个延时Intent，会把当前的意图进行封装保留，保证在当前app关闭后也能执行
        PendingIntent pendingIntent = PendingIntent.getActivity(UnityPlayer.currentActivity,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            //设置消息的发布通道，这个是安卓新版本的功能，用来统一控制消息的管道
            NotificationChannel channel = new NotificationChannel(notifyChannelId, notifyChannelId,
                    NotificationManager.IMPORTANCE_DEFAULT); //新建管道，并且设置消息优先级
            channel.setDescription(notifyChannelId); //做些信息配置
            channel.enableLights(true);
            channel.setSound(null, null);

            //获取消息通知中心的对象
            NotificationManager notificationManager =
                    (NotificationManager) UnityPlayer.currentActivity.getSystemService(Context.NOTIFICATION_SERVICE);
            //要求消息通知中心创建这个管道
            notificationManager.createNotificationChannel(channel);
            //创建一个消息的创建者
            NotificationCompat.Builder builder = new NotificationCompat.Builder(UnityPlayer.currentActivity, channel.getId());
            builder.setSmallIcon(R.drawable.notify_icon)
                    .setContentTitle(title)
                    .setContentText(textContent)
                    .setSmallIcon(R.drawable.notify_icon)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(textContent))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

//            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(UnityPlayer.currentActivity);
            //将消息创建者创建的消息发布到消息通知中心
            notificationManager.notify(notifyChannelId.hashCode(), builder.build());
        }else{
            Notification.Builder builder = new Notification.Builder(UnityPlayer.currentActivity)
                    .setContentTitle(title)
                    .setContentText(textContent)
                    .setSmallIcon(R.drawable.notify_icon)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setStyle(new Notification.BigTextStyle().bigText(textContent))
                    .setPriority(Notification.PRIORITY_DEFAULT);
            NotificationManager notificationManager =
                    (NotificationManager) UnityPlayer.currentActivity.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(notifyChannelId.hashCode(), builder.build());
        }
        Log.d("AlarmNotifyer", "SetNotify:" + notifyChannelId);
    }

    public void SetDelayNotify(String notifyChannelId, String title, String textContent, String secDelay, boolean isSet){
        int sec = 0;
        try {
            sec = Integer.parseInt(secDelay);
        }catch (NumberFormatException exception){
            Log.e("AlarmNotifyer", "SetNotifyDelay::Error::Can convert "+secDelay+" to number type, auto set zero.");
        }
        //新建Intent用来表示意图
        Intent intent = new Intent("com.playlib.alarmnotify.alarm_notification");
//        intent.setComponent(new ComponentName(UnityPlayer.currentActivity, UnityPlayerActivity.class));
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        intent.putExtra("title", title);
        intent.putExtra("textContent", textContent);
        intent.putExtra("notifyChannelId", notifyChannelId);
        int backgroundFlag = 0x01000000;
        intent.setFlags((int)(intent.getFlags() | backgroundFlag)); //激活背景执行

        AlarmManager alarmMgr = (AlarmManager) UnityPlayer.currentActivity.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(UnityPlayer.currentActivity, 0, intent, PendingIntent.FLAG_MUTABLE);

        if(isSet){
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * sec, alarmPendingIntent);
        }else{
            alarmMgr.cancel(alarmPendingIntent);
        }

        Log.d("AlarmNotifyer", "SetDelayNotify:" + notifyChannelId);
    }
}
